#!/usr/bin/env python
# encoding: utf-8
"""
aix.py
Telnet后台程序
Created by rikugun on 2010-08-12.
Copyright (c) 2010 TYDIC. All rights reserved.
"""

import telnetlib
import ConfigParser
import os
from tydic_utils.base import get_conf_path	

class TexudoBackend(object):
	"""
	Texudo后台
	可以设置 _DEBUG_LEVEL 开启telnet 调试
	"""
	__CONFIG_SETION__ = 'Tuxedo Backend'
	
	def __init__(self,config_path=get_conf_path()):
		super(TexudoBackend, self).__init__()
		self.config = ConfigParser.RawConfigParser()
		#print config_path
		self.config.read(config_path)
		self.instance = telnetlib.Telnet(host=self.get_conf('host'),
						timeout=int(self.get_conf('timeout')))
		self.instance.set_debuglevel(int(self.get_conf('debug_level')))
	def login(self):
		"""登录"""
		if self.get_conf('password'):
			self.instance.read_until("login: ")
			self.instance.write(self.get_conf('username')+'\n')
			self.instance.read_until("ssword: ")
			self.instance.write(self.get_conf('password')+'\n')
			self.instance.read_until('$ ')
		return True	
	def get_conf(self,name):
		"""从配置中获取参数"""
		return self.config.get(TexudoBackend.__CONFIG_SETION__,name)		
	def exe_cmd(self,cmd):
		"""执行命令
		@param cmd:执行的命令
		"""
		# print cmd
		self.instance.write(cmd+'\n')
		ret = self.instance.read_until('$ ').decode('GBK')
		if not bool(self.get_conf('quite')):
			print ret
		return ret	
	def close(self):
		"""关闭链接"""
		self.instance.close()	


